<?php
/**
 * WebmasterCity V3
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category	WebmasterCity V3
 * @package	 Authentication
 * @copyright   (c) Copyright 2009-2010 by wmcity.nl
 *
 * $Id: Doctrine.php 214 2009-06-18 21:24:03Z luckyluke56 $
 */

class UserController extends Zend_Controller_Action
{
	/**
	 * Tries to log in a user using Zend_Auth, and our custom
	 * Doctrine auth adapter
	 */
	public function loginAction()
	{
		$request = $this -> getRequest();
		$session = new Zend_Session_Namespace('auth');

		if($session -> logged_in)
		{
			$this -> _helper -> redirector('index', 'index');
		}
		else
		{
			$this -> view -> messages = array();

			$loginForm = new WMC_Form_Login();
			$loginForm -> submit -> setLabel('Inloggen');
			if($request -> isPost())
			{
				if($loginForm -> isValid($_POST))
				{
					// Try to authenticate
					$auth = Zend_Auth::getInstance();
					$adapter = new WMC_Auth_Adapter_Doctrine('User');
					$adapter -> setIdentity($loginForm -> getValue('username'))
						-> setCredential($loginForm -> getValue('password'));

					$result = $auth -> authenticate($adapter);
					switch($result -> getCode())
					{
						case Zend_Auth_Result::SUCCESS:
							$user = $adapter -> getResultRow();
							$session -> user_id = $user -> id;
							$session -> logged_in = true;

							$this -> _helper -> redirector('index', 'index');
							return;
						break;
						default:
							$this -> view -> messages[] = 'Gebruikersnaam/wachtwoord klopt niet';
					}
				}
			}

			$this -> view -> loginForm = $loginForm;
		}
	}

	/**
	 * Logs a user out
	 */
	public function logoutAction()
	{
		$session = new Zend_Session_Namespace('auth');

		if(!$session -> logged_in)
		{
			$this -> _helper -> redirector('login');
			return;
		}

		$session -> unsetAll();

		$this -> _helper -> redirector('index', 'index');
	}
}
